package com.hhb.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadOrderAccess {
    public static void main(String[] args) {
        ShareResource shareResource =new ShareResource();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                shareResource.print5();
            }
        },"第一个线程").start();

        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                shareResource.print10();
            }
        },"第二个线程").start();

        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                shareResource.print15();
            }
        },"第三个线程").start();
    }
}

class ShareResource{
    private int num = 1;
    private Lock lock = new ReentrantLock(false);
    private Condition condition1 =lock.newCondition();
    private Condition condition2 =lock.newCondition();
    private Condition condition3 =lock.newCondition();

    public void print5(){
        lock.lock();
        try {
            while (num!=1){
                condition1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println((i+1)+"次 "+Thread.currentThread().getName());
            }
            num=2;
            condition2.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print10(){
        lock.lock();
        try {
            while (num!=2){
                condition2.await();

            }
            for (int i = 0; i < 10; i++) {
                System.out.println((i+1)+"次 "+Thread.currentThread().getName());
            }
            num=3;
            condition3.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print15(){
        lock.lock();
        try {
            while (num!=3){
                condition3.await();

            }
            for (int i = 0; i < 15; i++) {
                System.out.println((i+1)+"次 "+Thread.currentThread().getName());
            }
            num=1;
            condition1.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
